#pragma once

#include <string>
#include <vector>

namespace solution_061
{

struct ListNode
{
    const int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) { }
    ListNode(int x) : val(x), next(nullptr) { }
    ListNode(int x, ListNode *next) : val(x), next(next) { }
};

class Solution
{
public:
    ListNode* rotateRight(ListNode* head, int k)
    {
        if (head == nullptr)
            return nullptr;

        int len = 1;
        auto tail = head;
        while (tail->next != nullptr) {
            tail = tail->next;
            ++len;
        }
        k %= len;

        if (k == 0)
            return head;

        auto step = len - k;
        auto new_tail = head;
        for (int i = 0; i < step - 1; ++i)
            new_tail = new_tail->next;

        auto new_head = new_tail->next;
        new_tail->next = nullptr;
        tail->next = head;
        return new_head;
    }
};

}  /* namespace solution_061 */
